import cartItem from './../../../template/cartItem.tpl'
import tools from './../../../utils/tools'

@tools
export default class Handle {
  constructor(courseData, cartData, oCart, observer) {
    this.courseData = courseData
    this.cartData = cartData
    this.oCart = oCart
    this.observer = observer

    this.init()
  }
  init () {
    this.observer.add(this.handleCartItem.bind(this))
  }
  handleCartItem (id, target, state) {
    console.log('handleCartItem',state);
    if (state) {
      const itemData = this.courseData.find((item) => item.id == id)
      
      const _item = Handle.createElement(
        'li',
        Handle.tplReplace(cartItem, {
          id: itemData.id,
          title: itemData.title,
          originPrice: itemData.coupon
            ? `<del>￥${itemData.price}.00</del>`
            : `￥${itemData.price}.00`,
          currentPrice: itemData.coupon
            ? `￥${Number(itemData.price) - Number(itemData.coupon)}.00`
            : Number(itemData.price),
        })
      )
      // 将文档碎片添加到课程列表容器
      this.oCart.appendChild(_item)
    } else {
      const oParent = target.parentNode
      oParent.remove()
    }
  }
}
